<?php
namespace app\user\controller;

use app\admin\model\user\User;
use think\facade\Cache;
use think\facade\Cookie;
use think\facade\Session;

class Index extends Base
{

    //个人 中心主页
    public function index()
    {
        return view();
    }

    //用户信息修改
    public function edit_user()
    {
        if($this->request->isPost())
        {
            $input = $this->request->post();
            $res = User::update($input,["id"=>_get_current_user_id()]);
            if($res)
            {
                $this->get_user();
                $this->success("修改成功");
            }else{
                $this->error("修改失败");
            }
        }
    }

    //用户邮箱验证
    public function user_bind_email()
    {
        if($this->request->isPost())
        {
            $input = $this->request->post();

            $user = $this->get_user();

            if($input['email_code']!=cache($input['email']."_email_code")) $this->error("请输入正确的邮箱验证码");

            if($input['email']==$user['email']) $this->success("验证成功");

            //邮箱更换
            $res = User::where('id',_get_current_user_id())
                ->update([
                    'email' => $input['email']
                ]);

            if($res)
            {
                Cache::clear($input['email']."_email_code");
                $this->get_user();
                $this->success('验证成功');
            }else{
                $this->error("绑定失败");
            }
        }
    }

    //用户 退出
    public function out()
    {
        Session::delete("user");
        Cookie::delete("user");
        $this->success("退出成功，即将跳转到主页");
    }

    //获取 并更新用户
    protected function get_user()
    {
        $user= User::where("id",_get_current_user_id())->find();
        if($user){
            unset($user['password']);
        }
        Cookie::set("user",$user);
        return $user;
    }

}